import * as vscode from "vscode";
import { TurboRenderer } from "./renderer";

export class PreviewPanel implements vscode.WebviewViewProvider {
  private view?: vscode.WebviewView;

  constructor(
    private readonly extensionUri: vscode.Uri,
    private renderer: TurboRenderer
  ) {}

  resolveWebviewView(webviewView: vscode.WebviewView) {
    this.view = webviewView;

    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [this.extensionUri],
    };

    webviewView.webview.html = this.getHtmlContent();
  }

  public async update(content: string) {
    if (this.view) {
      try {
        // 移除所有后处理逻辑，直接传递原始内容
        await this.view.webview.postMessage({
          type: "update",
          content: content, // 不再进行任何replace操作
        });
      } catch (err) {
        console.error("渲染异常:", err);
        this.showError(`渲染失败: ${err.message}`);
      }
    }
  }

  public showError(message: string) {
    if (this.view) {
      this.view.webview.postMessage({
        type: "error",
        content: `<div class="error">${message}</div>`,
      });
    }
  }

  private getHtmlContent() {
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <style>
          /* 核心修复：容器尺寸 */
          body {
            margin: 0;
            padding: 20px;
            overflow: hidden;
          }
          #content {
            width: 100%;
            min-height: 100vh;
            transform-origin: top left;
            transform: scale(1.4); /* 全局放大 */
          }
  
          /* foreignObject显示修复 */
          foreignObject {
            width: 100% !important;
            height: 100% !important;
            overflow: visible !important;
          }
          foreignObject div {
            min-width: 200px !important; /* 防止内容折叠 */
            padding: 12px !important;    /* 增大内边距 */
            font-size: 16px !important;  /* 放大文本 */
            line-height: 1.6 !important;
          }
  
          /* 防止重复渲染 */
          svg:not(:first-child) {
            display: none !important;
          }
        </style>
      </head>
      <body>
        <div id="content"></div>
        <script>
          const container = document.getElementById('content');
          let lastSVG = null;
  
          window.addEventListener('message', event => {
            if (event.data.type === 'update') {
              // 清除旧内容
              if (lastSVG) {
                lastSVG.remove();
              }
  
              // 创建新元素
              const parser = new DOMParser();
              const doc = parser.parseFromString(event.data.content, 'image/svg+xml');
              const svg = doc.documentElement;
              
              // 尺寸适配
              svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
              svg.style.width = '100%';
              svg.style.height = 'auto';
  
              // 注入文档
              container.appendChild(svg);
              lastSVG = svg;
            }
          });
        </script>
      </body>
      </html>
    `;
  }
}
